package com.ailesson.gateway.handler;


import com.ailesson.common.reply.R;
import com.ailesson.common.util.json.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static com.ailesson.common.except.GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR;

@Component
@Order(-1) // 保证优先级高于默认的 Spring Cloud Gateway 的 ErrorWebExceptionHandler 实现
@Slf4j
public class GlobalErrorHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()){
            return Mono.error(ex);
        }
        //错误转化为json返回
        R result = null;
        if (ex instanceof ResponseStatusException){
            result = responseStatusExceptionHandler(exchange, (ResponseStatusException) ex);
        }else{
            result = defaultExceptionHandler(exchange, (ResponseStatusException) ex);
        }
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        R finalResult = result;
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                return bufferFactory.wrap(JsonUtils.toJsonByte(finalResult));
            } catch (Exception e) {
                ServerHttpRequest request = exchange.getRequest();
                log.error("[输出返回结果错误：][uri({}/{}) 发生异常:{}]", request.getURI(), request.getMethod(), ex);
                return bufferFactory.wrap(new byte[0]);
            }
        }));
    }

    private R responseStatusExceptionHandler(ServerWebExchange exchange, ResponseStatusException ex) {
        ServerHttpRequest request = exchange.getRequest();
        log.error("[响应码异常:][uri({}:{}) 发生异常:{}]", request.getURI(), request.getMethod(), ex);
        return R.error(ex.getRawStatusCode(), "请求异常");
    }

    /**
     * 处理系统异常，兜底处理所有的一切
     */
    @ExceptionHandler(value = Exception.class)
    public R<?> defaultExceptionHandler(ServerWebExchange exchange,
                                                   Throwable ex) {
        ServerHttpRequest request = exchange.getRequest();
        log.error("[系统异常：][uri({}/{}) 发生异常:{}]", request.getURI(), request.getMethod(), ex);
        return R.error(INTERNAL_SERVER_ERROR.getCode(), INTERNAL_SERVER_ERROR.getMsg());
    }

}
